/**
 * JavaScript for the portal (the public part of the application)
 */

/**
 * The datagrid object
 * @private
 */
var dataGrid;

/**
 * The URL of the controller
 * @const
 */
var dataUrl = "data";

/**
 * The date filter
 * @private
 */
var datePicker = $('#datepicker').datetimepicker({
	pickTime: false
}).on('changeDate', function (ev, date) {
	HEALTH.callSetter("filter", {filterKey:"DATE",filterValue:ev.date.getTime()});
	HEALTH.reloadDataTable(dataGrid, dataUrl);
});

$(document).ready(function() {
	//set the date fitler value if present in the session
	if (window["dateFilterValue"] != "" && HEALTH.isNumber(window["dateFilterValue"])) {
		var dateValue = new Date(window["dateFilterValue"] * 1);
		$('#dateSelector').val(dateValue.getDay() + "." + (dateValue.getMonth() + 1) + "." + dateValue.getFullYear());
	}
	//dynamically add the options to the selects
	HEALTH.addOptionsAndSetValue('surgeryTypes', 'typeFilter', window["typeFilterValue"]);
	HEALTH.addOptionsAndSetValue('hospitals', 'hospitalFilter', window["hospitalFilterValue"]);
	//the change handlers
	$('#typeFilter').change(function() {
		HEALTH.callSetter("filter", {filterKey:"SURGERY_TYPE",filterValue:$('#typeFilter').val()});
		HEALTH.reloadDataTable(dataGrid, dataUrl);
	});
	$('#hospitalFilter').change(function() {
		HEALTH.callSetter("filter", {filterKey:"HOSPITAL",filterValue:$('#hospitalFilter').val()});
		HEALTH.reloadDataTable(dataGrid, dataUrl);
	});
	dataGrid = $('#dataGrid').dataTable({
		"bProcessing": false,
		"bPaginate": false,
		"bLengthChange": false,
		"bFilter": false,
		"bSort": false,
		"bInfo": false,
		"bAutoWidth": false,
		"sAjaxSource": dataUrl,
		"sAjaxDataProp": "",
		"aoColumns": [
			{
				"mDataProp": "day"
			},
			{
				"mDataProp": "start"
			},
			{
				"mDataProp": "end"
			},
			{
				"mDataProp": "type"
			},
			{
				"mDataProp": "hospital"
			},
			{
				"mDataProp": "doctor"
			},
			{
				"mData": function (dataSource, type, param) {
					if (dataSource["free"] == true) {
						return "<span class='label label-success'>" + window['freeText'] + "</span>";
					} else {
						return "<span class='label label-important'>" + window['reservedText'] + "</span>";
					}
				}
			}
		]
	});
	//register auto reload function
	setInterval(function () {
		HEALTH.reloadDataTable(dataGrid, dataUrl);
	}, 5000);
});